<?php

namespace App\Models\System;

use App\Libs\Tools\SystemCodeConstant;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract,
									Transformable
{
    use TransformableTrait,Authenticatable, Authorizable, CanResetPassword,EntrustUserTrait {
        EntrustUserTrait::can as entrustCan;
        Authorizable::can as authCan;
    }

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name','phone', 'email', 'password',
        'sex','wx_no','work_no','major_department_id','major_station_id',
        'direct_leader_user_id','account_status','remember_token','created_user','updated_user'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['remember_token'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     * 辅助部门
     */
    public function departments(){

        return $this->belongsToMany('App\Models\Personnel\Department','user_department','user_id','department_id')->withPivot(['created_user','type'])->withTimestamps();
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     * 辅助岗位
     */
    public function stations(){
        return $this->belongsToMany('App\Models\Personnel\Station','user_station','user_id','station_id')->withPivot(['created_user','type'])->withTimestamps();
    }


    /**
     * 判断是否离职
     */
    public function isLeave(){
        return $this->account_status==SystemCodeConstant::USER_ACCOUNT_STATUS_LEAVE;
    }

    public function can($permission, $param=false){
        $requireAll=false;
        $arguments=[];
        if(isset($param) && is_bool($param)){
            $requireAll=$param;
        }
        if(isset($param) && is_array($param)){
            $arguments=$param;
        }
        return $this->entrustCan($permission,$requireAll) || $this->authCan($permission,$arguments);
    }
}
